<template>
  <CommonPage title="菜单定义">
    <template #mid>
      <SearchForm>
        <template #extraButtons>
          <a-button type="primary" @click="showCreateModal">新增根菜单</a-button>
        </template>
      </SearchForm>
    </template>
    <SlTable :columns="columns" row-key="id" :data-source="tableData" :pagination="pagination" :loading="tableLoading">
      <template #bodyCell="{ column, record }: BodyCellOptions<Partial<MenuItem>>">
        <div v-if="column.key === 'oper'">
          <a
            v-if="record.type === MenuType.CATALOG || record.type === MenuType.MENU"
            class="mr-2"
            @click="addSubMenu(record)"
          >
            新增下级
          </a>
          <a @click="showUpdateModal(record)">编辑</a>
          <a class="ml-2 text-red-400" @click="handleDelete(record)">删除</a>
        </div>
      </template>
    </SlTable>
    <CURDDialog
      ref="CURDModalIns"
      id-key="id"
      :columns="columns"
      create-title="新增菜单"
      update-title="编辑菜单"
      delete-message="确认删除该菜单吗？"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :model-rules="modelRules"
      :table-data="tableData"
      :oper-data="operData"
      :curd="curd"
      :reload-table="reloadTable"
      @before-ok="beforeOk"
      @open="open"
    />
  </CommonPage>
</template>
<script lang="ts" setup>
import { ref, shallowRef } from "vue";
import { useI18n } from "/@/locales/useI18n";
import { useCURD } from "/@/hooks/useCURD";
import { FormItemComponentType, CURDAction, CURDDialogExpose } from "/@/components/CURDDialog/models";
import type { FormItemData, OperItem, ShowCURDModalOptions, CURDModalEvent } from "/@/components/CURDDialog/models";
import type { TableProps } from "ant-design-vue";
import { PatternKey } from "/@/utils/verify";
import { loopItem } from "/@/utils/treeData";
import { type MenuItem, MenuType } from "/@/api/main/system/models";
import { Api } from "/@/api/main/system";
import type { BodyCellOptions } from "/@/types/antd";

const { t } = useI18n();
const columns = ref<TableProps<Partial<MenuItem>>["columns"]>([
  {
    title: "名称",
    dataIndex: "name",
  },
  {
    title: "图标",
    dataIndex: "icon",
  },
  {
    title: "路径",
    dataIndex: "path",
  },
  {
    title: "类型",
    dataIndex: "type",
    customRender({ text }) {
      return t(`baseData.menuType.${text}`);
    },
  },
  {
    title: "权限编码",
    dataIndex: "perm",
  },
  // {
  //   title: "排序",
  //   dataIndex: "orderNum",
  // },
  {
    title: t("common.oper"),
    key: "oper",
    width: 100,
  },
]);
const model = ref<Partial<MenuItem>>({
  name: "",
  icon: "",
  path: "",
  type: "",
  perm: "",
  sort: 1,
});
const modelRules = ["menuName", "path", "menuType", "orderNum"];
function getMenuTypeData(superMenuItem?: MenuItem) {
  let data = [
    { label: "目录", value: MenuType.CATALOG },
    { label: "页面", value: MenuType.MENU },
    { label: "按钮", value: MenuType.BUTTON },
  ];
  if (superMenuItem) {
    if (superMenuItem.type === MenuType.MENU) {
      data.splice(0, 2);
    } else if (superMenuItem.type === MenuType.BUTTON) {
      data = [];
    }
  }
  return data;
}
const modelFormSetting: FormItemData<Partial<MenuItem>>[] = [
  {
    key: "name",
    max: 32,
    required: true,
    pattern: PatternKey.name,
  },
  {
    key: "type",
    label: "菜单类型",
    type: FormItemComponentType.SELECT,
    required: true,
    props: {
      options: getMenuTypeData(),
    },
  },
  {
    key: "sort",
    label: "显示排序",
    type: FormItemComponentType.NUMBER,
    props: {
      min: 0,
      max: 999,
    },
  },
  {
    key: "perm",
    label: "权限编码",
  },
];

const CURDModalIns = shallowRef<CURDDialogExpose>();
const showOptions = ref<ShowCURDModalOptions>();

function handleMenuSort(menuData?: MenuItem[]) {
  if (menuData && menuData.length > 0) {
    menuData.sort((a, b) => {
      return a.sort - b.sort;
    });
    menuData.forEach((menuItem) => {
      handleMenuSort(menuItem.children);
    });
  }
}

const { pagination, tableData, tableLoading, curd, reloadTable } = useCURD<MenuItem>({
  getDataUrl: Api.menuList,
  cudUrl: Api.menuList,
  restful: true,
  // mockData: getStaticMenuData(),
  loadFilter(data) {
    if (!data) return [];
    loopItem(data, (item) => {
      if (!item.children || item.children.length === 0) {
        item.children = void 0;
      }
    });
    handleMenuSort(data);
    return data;
  },
});
const curMenu = shallowRef<MenuItem>();
let curParentId: null | number = null;

const operData: OperItem<MenuItem>[] = [
  {
    label: t("common.edit"),
    handler: showUpdateModal,
  },
];
function showCreateModal() {
  curMenu.value = undefined;
  curParentId = 0;
  showOptions.value = { action: CURDAction.CREATE };
}
function showUpdateModal(record) {
  curMenu.value = undefined;
  curParentId = record.parentId;
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function handleDelete(record) {
  showOptions.value = { action: CURDAction.DELETE, record };
}
function beforeOk(e: CURDModalEvent<Partial<MenuItem>>) {
  if (e.model) {
    if (curParentId !== null) {
      e.model.parentId = curParentId;
    }
  }
}
function open(e: CURDModalEvent<Partial<MenuItem>>) {
  if (CURDModalIns.value) {
    CURDModalIns.value.toggleField("type", e.action === CURDAction.UPDATE);
  }
  if (e.formItemData && e.action === CURDAction.CREATE) {
    const target = e.formItemData.find((el) => el.key === "type");
    if (target && target.props) {
      target.props.options = getMenuTypeData(curMenu.value);
    }
  }
}

function addSubMenu(record) {
  curMenu.value = record;
  curParentId = record.id;
  showOptions.value = { action: CURDAction.CREATE };
}
</script>
